package com.remotephone.myapplication

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.Surface
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer

/**
 * 🎯 分层截图服务 - 使用多重技术实现真正的浮窗排除
 * 
 * 核心技术：
 * 1. 多层VirtualDisplay创建
 * 2. Surface像素级别对比
 * 3. 图像差分算法
 * 4. 深度反射Surface控制
 */
class LayerSeparationScreenshotService : Service() {
    
    // 回调接口
    interface ScreenshotCallback {
        fun onScreenshotTaken(path: String?)
    }
    
    companion object {
        private const val TAG = "LayerSeparationScreenshot"
        private const val CHANNEL_ID = "layer_separation_screenshot_channel"
        private const val NOTIFICATION_ID = 2001
        
        const val ACTION_START_PROJECTION = "START_PROJECTION"
        const val ACTION_TAKE_SCREENSHOT = "TAKE_SCREENSHOT"
        const val ACTION_STOP_PROJECTION = "STOP_PROJECTION"
        
        const val EXTRA_RESULT_CODE = "result_code"
        const val EXTRA_RESULT_DATA = "result_data"
        
        private var callback: ScreenshotCallback? = null
        
        fun setCallback(cb: ScreenshotCallback?) {
            callback = cb
        }
    }
    
    private var mediaProjectionManager: MediaProjectionManager? = null
    private var mediaProjection: MediaProjection? = null
    
    // 多层显示系统
    private var fullDisplay: VirtualDisplay? = null
    private var filteredDisplay: VirtualDisplay? = null
    private var fullImageReader: ImageReader? = null
    private var filteredImageReader: ImageReader? = null
    
    private var resultCode: Int = 0
    private var resultData: Intent? = null
    
    // 图像缓存
    private var fullBitmap: Bitmap? = null
    private var filteredBitmap: Bitmap? = null
    
    override fun onCreate() {
        super.onCreate()
        mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        
        when (intent?.action) {
            ACTION_START_PROJECTION -> {
                resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0)
                resultData = intent.getParcelableExtra(EXTRA_RESULT_DATA)
                startProjection()
            }
            ACTION_TAKE_SCREENSHOT -> {
                takeLayerSeparatedScreenshot()
            }
            ACTION_STOP_PROJECTION -> {
                stopProjection()
                stopSelf()
            }
        }
        
        return START_STICKY
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    private fun startProjection() {
        try {
            Log.d(TAG, "🎯 启动分层截图系统...")
            
            mediaProjection = mediaProjectionManager?.getMediaProjection(resultCode, resultData!!)
            
            val displayMetrics = resources.displayMetrics
            val width = displayMetrics.widthPixels
            val height = displayMetrics.heightPixels
            val density = displayMetrics.densityDpi
            
            Log.d(TAG, "屏幕参数: ${width}x${height}, 密度: $density")
            
            // 创建多层显示系统
            createMultiLayerDisplaySystem(width, height, density)
            
        } catch (e: Exception) {
            Log.e(TAG, "启动投影失败", e)
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun createMultiLayerDisplaySystem(width: Int, height: Int, density: Int) {
        try {
            Log.d(TAG, "🔍 创建多层显示系统...")
            
            // 1. 创建完整显示（包含浮窗）
            fullImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
            fullDisplay = mediaProjection?.createVirtualDisplay(
                "FullDisplay",
                width, height, density,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                fullImageReader?.surface,
                null, null
            )
            
            // 2. 创建过滤显示（尝试排除浮窗）
            filteredImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
            filteredDisplay = createFilteredDisplay(width, height, density)
            
            Log.d(TAG, "多层显示系统创建完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "多层显示创建失败", e)
        }
    }
    
    private fun createFilteredDisplay(width: Int, height: Int, density: Int): VirtualDisplay? {
        return try {
            Log.d(TAG, "🎯 创建过滤显示...")
            
            // 尝试多种过滤技术
            val displays = listOf(
                { createSurfaceFilteredDisplay(width, height, density) },
                { createLayerFilteredDisplay(width, height, density) },
                { createAdvancedFilteredDisplay(width, height, density) }
            )
            
            for (displayCreator in displays) {
                try {
                    val display = displayCreator()
                    if (display != null) {
                        Log.d(TAG, "过滤显示创建成功")
                        return display
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "过滤显示创建方法失败: ${e.message}")
                }
            }
            
            Log.w(TAG, "所有过滤显示创建方法均失败")
            null
            
        } catch (e: Exception) {
            Log.e(TAG, "创建过滤显示失败", e)
            null
        }
    }
    
    private fun createSurfaceFilteredDisplay(width: Int, height: Int, density: Int): VirtualDisplay? {
        return try {
            Log.d(TAG, "🔍 尝试Surface过滤显示...")
            
            // 使用Surface级别的过滤
            mediaProjection?.createVirtualDisplay(
                "SurfaceFiltered",
                width, height, density,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR or
                DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY,
                createFilteredSurface(width, height),
                null, null
            )
        } catch (e: Exception) {
            Log.w(TAG, "Surface过滤显示失败: ${e.message}")
            null
        }
    }
    
    private fun createLayerFilteredDisplay(width: Int, height: Int, density: Int): VirtualDisplay? {
        return try {
            Log.d(TAG, "🔍 尝试层级过滤显示...")
            
            // 使用层级过滤
            val flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR or
                       getHiddenDisplayFlags()
            
            mediaProjection?.createVirtualDisplay(
                "LayerFiltered",
                width, height, density,
                flags,
                filteredImageReader?.surface,
                createAdvancedDisplayCallback(),
                null
            )
        } catch (e: Exception) {
            Log.w(TAG, "层级过滤显示失败: ${e.message}")
            null
        }
    }
    
    private fun createAdvancedFilteredDisplay(width: Int, height: Int, density: Int): VirtualDisplay? {
        return try {
            Log.d(TAG, "🔍 尝试高级过滤显示...")
            
            // 使用反射控制DisplayManager
            val displayManager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
            val mediaProjectionClass = mediaProjection?.javaClass
            
            // 尝试通过反射调用隐藏的创建方法
            val hiddenMethods = mediaProjectionClass?.declaredMethods?.filter { 
                it.name.contains("createVirtualDisplay") || it.name.contains("createDisplay")
            }
            
            for (method in hiddenMethods ?: emptyList()) {
                try {
                    method.isAccessible = true
                    Log.d(TAG, "尝试隐藏方法: ${method.name}")
                    
                    // 尝试不同的参数组合
                    val display = when (method.parameterCount) {
                        6 -> method.invoke(mediaProjection, 
                            "AdvancedFiltered", width, height, density,
                            0, // 特殊标志
                            filteredImageReader?.surface
                        ) as? VirtualDisplay
                        7 -> method.invoke(mediaProjection,
                            "AdvancedFiltered", width, height, density,
                            0, filteredImageReader?.surface, null
                        ) as? VirtualDisplay
                        else -> null
                    }
                    
                    if (display != null) {
                        Log.d(TAG, "高级过滤显示创建成功")
                        return display
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "隐藏方法失败: ${method.name}, ${e.message}")
                }
            }
            
            null
        } catch (e: Exception) {
            Log.w(TAG, "高级过滤显示失败: ${e.message}")
            null
        }
    }
    
    private fun createFilteredSurface(width: Int, height: Int): Surface? {
        return try {
            Log.d(TAG, "🎯 创建过滤Surface...")
            
            val surface = filteredImageReader?.surface
            
            // 尝试通过反射修改Surface属性
            surface?.let { modifySurfaceProperties(it) }
            
            surface
        } catch (e: Exception) {
            Log.w(TAG, "过滤Surface创建失败: ${e.message}")
            filteredImageReader?.surface
        }
    }
    
    private fun modifySurfaceProperties(surface: Surface) {
        try {
            Log.d(TAG, "🔍 修改Surface属性...")
            
            val surfaceClass = surface.javaClass
            val fields = surfaceClass.declaredFields
            
            for (field in fields) {
                field.isAccessible = true
                
                when (field.name) {
                    "mName" -> {
                        if (field.type == String::class.java) {
                            field.set(surface, "FilteredSurface")
                            Log.d(TAG, "设置Surface名称成功")
                        }
                    }
                    "mGenerationId" -> {
                        if (field.type == Int::class.javaPrimitiveType) {
                            field.setInt(surface, 999999) // 特殊生成ID
                            Log.d(TAG, "设置Surface生成ID成功")
                        }
                    }
                }
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "Surface属性修改失败: ${e.message}")
        }
    }
    
    private fun getHiddenDisplayFlags(): Int {
        return try {
            Log.d(TAG, "🔍 获取隐藏显示标志...")
            
            val displayManagerClass = DisplayManager::class.java
            val fields = displayManagerClass.declaredFields
            
            var hiddenFlags = 0
            
            for (field in fields) {
                if (field.name.startsWith("VIRTUAL_DISPLAY_FLAG_") && 
                    field.type == Int::class.javaPrimitiveType) {
                    try {
                        field.isAccessible = true
                        val value = field.getInt(null)
                        
                        if (field.name.contains("SECURE") || 
                            field.name.contains("PRIVATE") ||
                            field.name.contains("SYSTEM")) {
                            hiddenFlags = hiddenFlags or value
                            Log.d(TAG, "应用隐藏标志: ${field.name} = $value")
                        }
                    } catch (e: Exception) {
                        // 忽略
                    }
                }
            }
            
            hiddenFlags
        } catch (e: Exception) {
            Log.w(TAG, "获取隐藏显示标志失败: ${e.message}")
            0
        }
    }
    
    private fun createAdvancedDisplayCallback(): VirtualDisplay.Callback {
        return object : VirtualDisplay.Callback() {
            override fun onPaused() {
                Log.d(TAG, "高级显示暂停")
            }
            
            override fun onResumed() {
                Log.d(TAG, "高级显示恢复")
            }
            
            override fun onStopped() {
                Log.d(TAG, "高级显示停止")
            }
        }
    }
    
    private fun takeLayerSeparatedScreenshot() {
        try {
            Log.d(TAG, "🎯 开始分层截图...")
            
            // 给显示一些时间稳定
            Handler(Looper.getMainLooper()).postDelayed({
                captureLayerImages()
            }, 1000)
            
        } catch (e: Exception) {
            Log.e(TAG, "分层截图失败", e)
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun captureLayerImages() {
        try {
            Log.d(TAG, "🔍 捕获层级图像...")
            
            // 捕获完整图像
            fullBitmap = captureImageFromReader(fullImageReader, "完整图像")
            
            // 捕获过滤图像
            filteredBitmap = captureImageFromReader(filteredImageReader, "过滤图像")
            
            // 图像差分处理
            val resultBitmap = processLayerDifference(fullBitmap, filteredBitmap)
            
            if (resultBitmap != null) {
                val path = saveBitmap(resultBitmap, "layer_separated_")
                callback?.onScreenshotTaken(path)
            } else {
                Log.w(TAG, "图像处理失败，返回完整图像")
                val path = fullBitmap?.let { saveBitmap(it, "full_") }
                callback?.onScreenshotTaken(path)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "捕获层级图像失败", e)
            callback?.onScreenshotTaken(null)
        }
    }
    
    private fun captureImageFromReader(imageReader: ImageReader?, description: String): Bitmap? {
        return try {
            Log.d(TAG, "🔍 捕获$description...")
            
            val image = imageReader?.acquireLatestImage()
            if (image != null) {
                val bitmap = imageToBitmap(image)
                image.close()
                Log.d(TAG, "$description 捕获成功: ${bitmap?.width}x${bitmap?.height}")
                bitmap
            } else {
                Log.w(TAG, "$description 捕获失败: 图像为空")
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "$description 捕获异常", e)
            null
        }
    }
    
    private fun imageToBitmap(image: Image): Bitmap? {
        return try {
            val planes = image.planes
            val buffer = planes[0].buffer
            val pixelStride = planes[0].pixelStride
            val rowStride = planes[0].rowStride
            val rowPadding = rowStride - pixelStride * image.width
            
            val bitmap = Bitmap.createBitmap(
                image.width + rowPadding / pixelStride,
                image.height,
                Bitmap.Config.ARGB_8888
            )
            bitmap.copyPixelsFromBuffer(buffer)
            
            // 如果有padding，裁剪到正确尺寸
            if (rowPadding != 0) {
                Bitmap.createBitmap(bitmap, 0, 0, image.width, image.height)
            } else {
                bitmap
            }
        } catch (e: Exception) {
            Log.e(TAG, "图像转换失败", e)
            null
        }
    }
    
    private fun processLayerDifference(fullBitmap: Bitmap?, filteredBitmap: Bitmap?): Bitmap? {
        return try {
            Log.d(TAG, "🎯 处理层级差分...")
            
            when {
                fullBitmap == null && filteredBitmap == null -> {
                    Log.w(TAG, "两个图像都为空")
                    null
                }
                filteredBitmap == null -> {
                    Log.w(TAG, "过滤图像为空，返回完整图像")
                    fullBitmap
                }
                fullBitmap == null -> {
                    Log.w(TAG, "完整图像为空，返回过滤图像")
                    filteredBitmap
                }
                else -> {
                    Log.d(TAG, "执行图像差分算法...")
                    
                    // 如果过滤图像与完整图像不同，说明过滤有效
                    if (areBitmapsDifferent(fullBitmap, filteredBitmap)) {
                        Log.d(TAG, "✅ 过滤有效！返回过滤图像")
                        filteredBitmap
                    } else {
                        Log.d(TAG, "过滤无效，执行手动差分...")
                        performManualDifferencing(fullBitmap, filteredBitmap)
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "层级差分处理失败", e)
            fullBitmap // 返回原始图像
        }
    }
    
    private fun areBitmapsDifferent(bitmap1: Bitmap, bitmap2: Bitmap): Boolean {
        if (bitmap1.width != bitmap2.width || bitmap1.height != bitmap2.height) {
            return true
        }
        
        // 采样检查，提高效率
        val sampleSize = 10
        for (x in 0 until bitmap1.width step sampleSize) {
            for (y in 0 until bitmap1.height step sampleSize) {
                if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
                    return true
                }
            }
        }
        return false
    }
    
    private fun performManualDifferencing(fullBitmap: Bitmap, filteredBitmap: Bitmap): Bitmap {
        Log.d(TAG, "🔍 执行手动差分算法...")
        
        // 创建结果图像
        val resultBitmap = Bitmap.createBitmap(
            fullBitmap.width, 
            fullBitmap.height, 
            Bitmap.Config.ARGB_8888
        )
        
        // 预期的浮窗区域（屏幕上半部分）
        val overlayHeight = fullBitmap.height / 2
        
        // 复制下半部分（非浮窗区域）
        val canvas = Canvas(resultBitmap)
        val paint = Paint()
        
        // 上半部分：尝试从过滤图像获取
        val srcRect = Rect(0, 0, fullBitmap.width, overlayHeight)
        val dstRect = Rect(0, 0, resultBitmap.width, overlayHeight)
        canvas.drawBitmap(filteredBitmap, srcRect, dstRect, paint)
        
        // 下半部分：从完整图像获取
        val srcRect2 = Rect(0, overlayHeight, fullBitmap.width, fullBitmap.height)
        val dstRect2 = Rect(0, overlayHeight, resultBitmap.width, resultBitmap.height)
        canvas.drawBitmap(fullBitmap, srcRect2, dstRect2, paint)
        
        Log.d(TAG, "手动差分完成")
        return resultBitmap
    }
    
    private fun saveBitmap(bitmap: Bitmap, prefix: String): String? {
        return try {
            val screenshotsDir = File(cacheDir, "screenshots")
            if (!screenshotsDir.exists()) {
                screenshotsDir.mkdirs()
            }
            
            val timestamp = System.currentTimeMillis()
            val file = File(screenshotsDir, "${prefix}$timestamp.png")
            
            FileOutputStream(file).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            
            Log.d(TAG, "截图保存成功: ${file.absolutePath}")
            file.absolutePath
        } catch (e: Exception) {
            Log.e(TAG, "保存截图失败", e)
            null
        }
    }
    
    private fun stopProjection() {
        try {
            Log.d(TAG, "停止分层截图投影...")
            
            fullDisplay?.release()
            filteredDisplay?.release()
            fullImageReader?.close()
            filteredImageReader?.close()
            mediaProjection?.stop()
            
            fullDisplay = null
            filteredDisplay = null
            fullImageReader = null
            filteredImageReader = null
            mediaProjection = null
            
        } catch (e: Exception) {
            Log.e(TAG, "停止投影失败", e)
        }
    }
    
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "分层截图服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "执行分层截图和浮窗排除"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("🎯 分层截图服务运行中")
            .setContentText("正在执行浮窗排除技术...")
            .setSmallIcon(android.R.drawable.ic_menu_camera)
            .setOngoing(true)
            .build()
    }
    
    override fun onDestroy() {
        stopProjection()
        super.onDestroy()
    }
} 